<template>
  <div ref="imgTooles">
    <a-form-model-item :prop="required ? prop : ''">
      <!-- {{ options.disabled }} {{options.pattern}} -->
      <!-- 上传图片 -->
      <div v-if="fileType == 'uploadImg'">
        <!-- 预览模式描述 -->
        <span v-if="options.pattern == 2 && options.disabled == true">
          {{ options.explain }}
        </span>
        <a-upload
          v-else-if="options.pattern == 1 || ([2, 3].includes(options.pattern) && options.disabled == false)"
          :style="`width: ${options.width}; word-wrap:break-word;`"
          accept="image/*"
          :list-type="options.listType"
          :customRequest="uploadFile"
          @change="handleChange"
          @click="helpClick"
          @preview="handlePreview"
          :file-list="fileList"
          :disabled="options.disabled"
        >
          <div v-if="fileList.length < options.limit || options.multiple">
            <!-- 按钮样式上传 -->
            <div v-if="options.listType != 'picture-card'">
              <a-button> <a-icon type="upload" /> {{ options.placeholder }} </a-button>
            </div>
            <!-- 图片样式上传 -->
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">{{ options.placeholder }}</div>
            </div>
          </div>
        </a-upload>
        <div v-else :style="`width: ${options.width}; word-wrap:break-word;`">
          <div v-if="fileList.length > 0">
            <span v-for="item in fileList" :key="item.uid">
              <img @click="imageChange" :data-original="item.url" class="imgItem" :src="item.url" alt="" />
            </span>
          </div>
          <div v-else :class="{'formMaringBox': true, 'beyond_hiding': index == undefined ? false : true}"></div>
        </div>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </div>

      <!-- 上传附件 -->
      <div v-else>
        <!-- 预览模式描述 -->

        <span v-if="options.pattern == 2 && options.disabled == true">
          {{ options.explain }}
        </span>
        <div v-else-if="options.pattern == 1 || ([2, 3].includes(options.pattern) && options.disabled == false)">
          <!-- 拖拽上传 -->
          <a-upload-dragger
            v-if="options.drag"
            :style="`width: ${options.width}; word-wrap:break-word;`"
            :customRequest="uploadFile"
            @change="handleChange"
            @click="helpClick"
            @preview="fileView"
            :file-list="fileList"
            name="file"
            :multiple="true"
            :disabled="options.disabled"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">单击或拖动文件到此区域上传</p>
          </a-upload-dragger>
          <!-- 手动上传 -->
          <a-upload
            v-else
            :style="`width: ${options.width}; word-wrap:break-word;`"
            :customRequest="uploadFile"
            @change="handleChange"
            @click="helpClick"
            @preview="fileView"
            :file-list="fileList"
            name="file"
            :multiple="true"
            :disabled="options.disabled"
          >
            <div v-if="fileList.length < options.limit || options.multiple">
              <a-button> <a-icon type="upload" /> {{ options.placeholder }} </a-button>
            </div>
          </a-upload>
        </div>
        <div v-else :style="`width: ${options.width}; word-wrap:break-word;`">
          <div v-if="fileList.length > 0">
            <div @click="fileView(item)" class="fileItem" v-for="item in fileList" :key="item.uid">
              <a-icon type="file" /> {{ item.name.substring(0, item.name.indexOf('.')) }}
            </div>
          </div>
          <div v-else :class="{'formMaringBox': true, 'beyond_hiding': index == undefined ? false : true}"></div>
        </div>
      </div>
    </a-form-model-item>

    <!-- 附件预览弹框 -->
    <a-modal v-model="isModel" title="附件预览" :footer="null" destroyOnClose>
      <a-spin :spinning="spinning" >
      <iframe  :src="fileurl" @load="loaded"></iframe>
    </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { minioUpload, getFile } from '@/api/base/file.js'
import Viewer from 'viewerjs'
import { KKFILE_URL } from '@/store/mutation-types'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  props: {
    // 要上传的文件类型
    fileType: {
      type: String,
      default: 'uploadImg',
    },
    required: {
      type: Boolean,
      default: true,
    },
    label: {
      type: String,
    },
    span: {
      type: Number,
      default: 24,
    },
    prop: {
      type: String,
    },
    type: {
      type: String,
      default: 'table',
    },
    // 子表单用到
    index: {
      type: Number,
    },
    value: {},
    // 属性配置参数
    options: {
      type: Object,
      default() {
        return {}
      },
    },
    // 布局配置参数
    config: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      fileurl: '', // 文件预览地址
      spinning: true, // 加载状态
      isModel: false, // 附件预览弹框
      // urlRoot: util.getRoot(window.location.href),
      previewVisible: false,
      previewImage: '',
      fileList: [], // 文件列表
      loading: false,
    }
  },
  created() {
    if (this.value && this.value.length > 0) {
      this.getFileData(this.value)
    }
  },
  watch: {
    value(val, oldVal) {
      this.fileList.length = 0
      if(val) {
        this.getFileData(val)
      }
     }
  },
  methods: {
    loaded() {
      this.spinning = false
    },
    // 图片添加点击事件
    initImageTools() {
      const viewer = new Viewer(this.$refs.imgTooles, {
        url: 'data-original',
        show: function () {
          viewer.update()
        },
        hide: function () {
          //在图片消失的时候销毁viewer
          viewer.destroy()
        },
      })
    },
    //点击图片创建实例 点击事件绑定在图片上
    imageChange(e) {
      if (e.target.nodeName == 'IMG') {
        // console.log('图片', e)
        this.initImageTools()
      }
    },
    // 附件在线预览
    fileView(file) {
      console.log('文件预览', file)
      // this.fileurl = KKFILE_URL + '/preview/onlinePreview?url=' + encodeURIComponent(file.url)
      // this.isModel = true
      window.open(KKFILE_URL + '/preview/onlinePreview?url=' + encodeURIComponent(file.url))
    },
    // 附件回显
    getFileData(ids) {
      let idArr = ids.split(',')
      idArr.forEach((v) => {
        getFile({ id: v }).then((res) => {
          // console.log('附件回显', res)
          let file = {
            uid: res.data.id,
            name: res.data.filename,
            status: 'done',
            url: res.data.url,
          }

          this.fileList.push(file)
        })
      })
    },
    helpClick() {
      if (this.options.click) {
        this.$emit('fHelp', this.options.click, this.index)
      }
    },
    handleCancel() {
      this.previewVisible = false
    },
    // 图片预览
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },

    // 图片上传前校验
    handleChange({ fileList }) {
      if (this.options.change) {
        this.$emit('fHelp', this.options.change, this.index)
      }
      for (var i = 0; i < fileList.length; i++) {
        if (fileList[i].size / 1024 / 1024 > 20) {
          this.$message.warning('pdf文件不能大于20M')
          return
        }
      }
      this.fileList = fileList
      if (!this.loading) {
        this.updateDataF(this.fileList || [])
      }
      // console.log('上传前', fileList)
    },
    // 图片上传
    uploadFile(data) {
      // 上传文件
      this.loading = true
      minioUpload(data.file).then((res) => {
        // console.log('上传文件', res)
        if (res.code == 0) {
          data.onSuccess()
          this.fileList[this.fileList.length - 1]['uid'] = res.data.id
        }
        this.loading = false
        this.updateDataF(this.fileList || [])
        // console.log('上传后', this.fileList)
      })
    },
    updateDataF(fileData) {
      let ids = fileData.map((v) => {
        return v.uid
      })
      console.log('更新id', ids, typeof ids.join(','))
      // 文件id以逗号分隔
      this.$emit('updatedValueF', this.prop, ids.join(','), this.index)
      // 重新触发一次校验
      this.$listeners.f_updateCheck(this.prop)
    },
  },
}
</script>

<style lang="less" scoped>
.imgItem {
  // width: 100px;
  height: 100px;
  border: 1px solid rgb(247, 243, 243);
  margin-right: 10px;
}
.fileItem {
  font-weight: 800;
}
.fileItem:hover {
  color: rgb(138, 197, 236);
  cursor: pointer;
}
.imgBox {
  width: 100px;
  height: 100px;
}
.uploadBox {
  float: left;
}
</style>

